package com.fmi.timedealer.achievement;

import com.fmi.timedealer.R;
import com.fmi.timedealer.datamanager.IDataManager;
import com.fmi.timedealer.datamanager.SQLiteDataManager;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class ManageAchievementActivity extends Activity {
	
	private Achievement currentAchievement = null;
	private IDataManager dbManager = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.manage_achievement);
		dbManager = new SQLiteDataManager("MyDB", this);
		
		Bundle extras = getIntent().getExtras();
		currentAchievement = (Achievement)extras.getSerializable(AchievementsActivity.ACHIEVEMENT_BUNDLE_KEY);
		fillViewsData(currentAchievement);
		
		Button btnSave = (Button)findViewById(R.id.btn_save_achievement);
		btnSave.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				updateCurrentAchievementValues();
				if (currentAchievement.getId() == 0) {
					dbManager.insertAchievement(currentAchievement);
				}
				else {
					dbManager.updateAchievement(currentAchievement);
				}
				returnResult(Activity.RESULT_OK);
			}
		});
		
		Button btnCancel = (Button)findViewById(R.id.btn_cancel_achievement);
		btnCancel.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				returnResult(Activity.RESULT_CANCELED);
			}
		});
	}
	
	private void updateCurrentAchievementValues() {
			
			// Fill Name data
			TextView tvAchName = (TextView)findViewById(R.id.achievement_name);
			if (tvAchName != null) {
				currentAchievement.setName(tvAchName.getText().toString());
			}
			
			// Fill Goal Message data
			TextView tvAchGoal = (TextView)findViewById(R.id.achievement_goal);
			if (tvAchGoal != null) {
				currentAchievement.setGoalMessage(tvAchGoal.getText().toString());
			}
	}
	
	private void fillViewsData(Achievement achievement) {
		
		// Fill Name data
		TextView tvAchName = (TextView)findViewById(R.id.achievement_name);
		if (tvAchName != null) {
			tvAchName.setText(achievement.getName());
		}
		
		// Fill Goal Message data
		TextView tvAchGoal = (TextView)findViewById(R.id.achievement_goal);
		if (tvAchGoal != null) {
			tvAchGoal.setText(achievement.getGoalMessage());
		}
	}
	
	private void returnResult(int resultCode) {

		if (resultCode == RESULT_OK) {
			getIntent().removeExtra(AchievementsActivity.ACHIEVEMENT_BUNDLE_KEY);
			getIntent().putExtra(AchievementsActivity.ACHIEVEMENT_BUNDLE_KEY, currentAchievement);
		}
		this.setResult(resultCode, getIntent());
		this.finish();
	}

}
